package com.bkitmobile.kesu.android.GUI;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bkitmobile.kesu.android.ClassInfo.CmtLocation;
import com.bkitmobile.kesu.android.ClassInfo.FriendShortInfo;
import com.bkitmobile.kesu.android.ClassInfo.LocationUserInfo;
import com.bkitmobile.kesu.android.ClassInfo.PlaceInfo;
import com.bkitmobile.kesu.android.connectServer.LoadPlaceInfo;
import com.bkitmobile.kesu.android.connectServer.Request;
import com.bkitmobile.kesu.android.connectServer.ServiceCallback;
import com.bkitmobile.kesu.android.connectServer.staticClass;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class KesuMap extends MapActivity implements OnClickListener, OnKeyListener{
	private MapView map;
	private ViewGroup zoom;
	private MyLocationOverlay me=null;
	private GeoPoint myPoint, tapPoint;
	private List<FriendShortInfo> fListInfo;
	private List<LocationUserInfo> listUserLocation;
	private Location myLocation;
	private Paint bluePaint;
	private Paint grayPaint;
	private Paint redPaint;
	private boolean isManage;
	private static int markerRadius = 7;
	private Drawable marker;
	private boolean isAddingNewPlace;
	private LinearLayout containerInfo, containerConfirmAdd;
	private TextView txtPlaceInfo;
	private Button btnViewCmt, btnLike, btnAdd, btnCancel, btnViewInfo;
	private ImageButton btnEdit,btnDirect;
	private Dialog dlgAddPlace, dlgCmt; 
	private HashMap<String,Overlay> mapPlaceOverlays;
	private List<PlaceOverlay> listPlaceOverlays;
	private HashMap<String,PlaceInfo> placesInfo;
	private HashMap<String,PlaceInfo> favoritePlaces;
	private HashMap<String,PlaceInfo> nearPlaces;
	private HashMap<String,PlaceInfo> personalPlaces;
	private boolean isTapOnPlace = false;
	private PlaceInfo pInfo;
	private boolean isFavorite;
	private boolean isNear;
	private boolean isLoadFav;;
	private boolean isLoadNear;
	private LoadPlaceInfo loadInfo;
	private double myLat,myLng;
	private PointOverlay pointOverlay;
	//private FriendsOverlay fOverlay;
	private Handler handler = new Handler();
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		favoritePlaces = new HashMap<String, PlaceInfo>();
		nearPlaces = new HashMap<String, PlaceInfo>();
		personalPlaces = new HashMap<String, PlaceInfo>();
		map=(MapView)findViewById(R.id.map);
		zoom=(ViewGroup)findViewById(R.id.zoom);
		containerInfo = (LinearLayout) findViewById(R.id.map_main_infoContainer);
		containerConfirmAdd = (LinearLayout) findViewById(R.id.map_main_confirmAdd);
		txtPlaceInfo = (TextView) findViewById(R.id.map_main_placeInfo);
		btnViewCmt = (Button) findViewById(R.id.map_main_viewCmt);
		btnLike = (Button) findViewById(R.id.map_main_like);
		btnAdd = (Button) findViewById(R.id.map_main_add);
		btnCancel = (Button) findViewById(R.id.map_main_cancel);
		btnViewInfo = (Button) findViewById(R.id.map_main_viewinfo);
		btnEdit = (ImageButton) findViewById(R.id.map_main_edit);
		btnDirect = (ImageButton) findViewById(R.id.map_main_direction);
		btnViewCmt.setOnClickListener(this);
		btnViewInfo.setOnClickListener(this);
		btnLike.setOnClickListener(this);
		btnAdd.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		btnEdit.setOnClickListener(this);
		btnDirect.setOnClickListener(this);
		zoom.addView(map.getZoomControls());
		map.getController().setZoom(20);
		Bundle extras = getIntent().getExtras();
		mapPlaceOverlays = new HashMap<String, Overlay>();
		listPlaceOverlays = new LinkedList<PlaceOverlay>();
		isManage = extras.getBoolean("manage");
		marker=getResources().getDrawable(R.drawable.flag);
		marker.setBounds(-marker.getIntrinsicWidth()/2, 
				-marker.getIntrinsicHeight()/2, 
				marker.getIntrinsicWidth()/2, 
				marker.getIntrinsicHeight()/2);
		isAddingNewPlace = false;
		if (!isManage)
		{
			initPersonLocation(extras);
			initPlaceLocation(extras);
			initLoadFilter();
			
		} else {
			initManageLocation(extras);
		}
	}
	private void initLoadFilter()
	{
		loadInfo = new LoadPlaceInfo(myLat, myLng,this){

			@Override
			public void onFailure(Exception exception) {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						StaticDialogs.okButtonDialog(KesuMap.this
								, KesuMap.this.getString(R.string.disconnect));
					}
				});
			}

			@Override
			public void onSuccess(final String result) {
				// TODO Auto-generated method stub
				handler.post(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							JSONArray listPlace = new JSONArray(result);
							for (int i = 0 ; i < listPlace.length() ; i++)
							{
								JSONObject object = listPlace.getJSONObject(i);
								double lat = object.getDouble("lat");
								double lng = object.getDouble("lng");
								String name = object.getString("name");
								String type = object.getString("type");
								GeoPoint point = staticClass.getPoint(lat, lng);
								PlaceInfo info = new PlaceInfo(name, type
										, point.getLatitudeE6(), point.getLongitudeE6());
								PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(type);
								if (overlay != null)
								{
									overlay.addItems(point, name);
								} else {
									overlay = new PlaceOverlay(staticClass.getDrawable(type,KesuMap.this), type);
									overlay.addItems(point, name);
									mapPlaceOverlays.put(type, overlay);
									listPlaceOverlays.add(overlay);
									map.getOverlays().add(overlay);
									Log.d("overlay", type);
								}
								Log.d("add", type);
								placesInfo.put(point.getLatitudeE6()+""+point.getLongitudeE6(), info);
								if (isNear) nearPlaces.put(info.getLatE6()+""+info.getLngE6(), info);
								else if (isFavorite) favoritePlaces.put(info.getLatE6()+""+info.getLngE6(), info);
							}
						} catch (JSONException e){
							
						}
					}
				});
			}
			
		};
	}
	
//	private int posIndex;
	private class PlaceOverlay extends ItemOverlay
	{
		private boolean getInfo = false;
		List<Object> listAlert = null;
		public PlaceOverlay(Drawable marker, String type) {
			super(marker, type);
			// TODO Auto-generated constructor stub
			listAlert = new LinkedList<Object>();
		}
		
		private void requestInfo(int index)
		{
			pInfo = placesInfo.get(
					items.get(index).getPoint().getLatitudeE6()+
					""+items.get(index).getPoint().getLongitudeE6());
			final GeoPoint pPoint = items.get(index).getPoint();
			if (!pInfo.isEnable()){
				String []identities = {"ID","lat","lng"};
				String []atributies = {Request.GET_PLACE_INFO,
						String.valueOf(pPoint.getLatitudeE6()),
						String.valueOf(pPoint.getLongitudeE6())};
				Request.sendAndRecieveData(identities, atributies, true,KesuMap.this,new ServiceCallback<String>() {
					
					@Override
					public void onSuccess(final String result) {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								try {
									JSONObject obj = new JSONObject(result);
									boolean like = obj.getBoolean("like");
									String userCreate = obj.getString("userCreate");
									String info = obj.getString("info");
									String addr = obj.getString("addr");
									JSONArray lsCmt = new JSONArray(obj.getString("cmt"));
									List<CmtLocation> listCmt = new ArrayList<CmtLocation>();
									for (int i = 0 ; i < lsCmt.length() ; i++)
									{
										JSONObject newObj = lsCmt.getJSONObject(i);
										String user = newObj.getString("user");
										String cmt = newObj.getString("cmt");
										String time = newObj.getString("time");
										Log.d("obj", newObj.toString());
										CmtLocation newCmt = new CmtLocation(user, cmt,time);
										listCmt.add(newCmt);
									}
									pInfo.enable(listCmt, userCreate, info, addr, like);		
									setPlaceInfo(pInfo.getName(), pInfo.getType(), pInfo.getAddress(), pInfo.getInfo());
									Log.d("MAP", "Click");
									isTapOnPlace = true;
									if(map.getZoomLevel() < map.getMaxZoomLevel()){
										map.getController().setCenter(pPoint);
										map.getController().zoomIn();
									}
									String []types = KesuMap.this.getResources().getStringArray(R.array.map_items_public);
									if(pInfo.getType().equals(types[0])){
										btnEdit.setVisibility(View.VISIBLE);
									}
									else if(isPublicPlace(pInfo.getType())){
										btnEdit.setVisibility(View.VISIBLE);
									}
									else{
										btnEdit.setVisibility(View.INVISIBLE);
									}
									containerInfo.setVisibility(View.VISIBLE);
									if (pInfo.isLike()) btnLike.setText("Dislike");
									else btnLike.setText("Like");
								} catch (JSONException e)
								{
									
								}
							}
						});
						
					}
					@Override
					public void onFailure(Exception exception) {
						// TODO Auto-generated method stub
						handler.post(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								StaticDialogs.okButtonDialog(KesuMap.this
										, KesuMap.this.getString(R.string.disconnect));
							}
						});
						
					}
				});
			} else {
				setPlaceInfo(pInfo.getName(), pInfo.getType(), pInfo.getAddress(), pInfo.getInfo());
				Log.d("MAP", "Click");
				isTapOnPlace = true;
				if(map.getZoomLevel() < map.getMaxZoomLevel()){
					map.getController().setCenter(pPoint);
					map.getController().zoomIn();
				}
				containerInfo.setVisibility(View.VISIBLE);
				if (pInfo.isLike()) btnLike.setText("Dislike");
				else btnLike.setText("Like");
			}
		}
		@Override
		public void init(final int index) {
			// TODO Auto-generated method stub
			pInfo = placesInfo.get(
					items.get(index).getPoint().getLatitudeE6()+
					""+items.get(index).getPoint().getLongitudeE6());
			AlertDialog tmp = new AlertDialog.Builder(KesuMap.this)
        	.setTitle("Confirm message")
        	.setMessage("Do you want view " + pInfo.getName() + " info?")
        	.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						try {
							setGetInfo(true);
							for (int i = 0 ; i < listAlert.size() ; i++)
							{
								((AlertDialog) listAlert.get(i)).dismiss();
							}
							requestInfo(index);
							listAlert = new LinkedList<Object>();
						} catch (Exception e)
						{
						}
					}
				}
	        )
	        .setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					try {
						setGetInfo(false);
					} catch (Exception e)
					{
						
					}
					
				}
			}).create();
			listAlert.add(tmp);
			tmp.show();
		}

		public void setGetInfo(boolean getInfo) {
			this.getInfo = getInfo;
		}

		public boolean isGetInfo() {
			return getInfo;
		}
	}
	private class PointOverlay extends ItemOverlay
	{
		private OverlayItem tmp;;
		public PointOverlay(Drawable defaultMarker) {
			super(defaultMarker);
			// TODO Auto-generated constructor stub
			tmp = null;
			populate();
		}
		@Override
		public void init(int index) {
			// TODO Auto-generated method stub
		}
		
		public void removeItem()
		{
			items.remove(tmp);
			populate();
		}
		@Override
		public boolean onTap(GeoPoint p, MapView mapView) {
			if(isAddingNewPlace){
				if(map.getZoomLevel() < map.getMaxZoomLevel()){
					map.getController().zoomIn();
					map.getController().setCenter(p);
				}
				tapPoint = p;
				containerConfirmAdd.setVisibility(View.VISIBLE);
				containerInfo.setVisibility(View.INVISIBLE);
				if (tmp!= null) items.remove(tmp);
				tmp = new OverlayItem(
						staticClass.getPoint((double)(p.getLatitudeE6())/1E6, (double) (p.getLongitudeE6())/1E6)
		        		  , "Create new Location", "here");
				items.add(tmp);
				populate();
			}
			else {
				if(containerInfo.getVisibility() == View.VISIBLE){
					try {
						Thread.sleep(100);
						if(!isTapOnPlace){
							containerInfo.setVisibility(View.INVISIBLE);
						}
						isTapOnPlace = false;
					} catch (InterruptedException e) {
					}
				}
			}
			return true;
		}
	}
	private void initPlaceLocation(Bundle data) {
		// TODO Auto-generated method stub
		placesInfo = new HashMap<String, PlaceInfo>();
		int size = data.getInt("psize");
		isNear = data.getBoolean("isNear");
		isFavorite = data.getBoolean("isFavorite");
		isLoadFav = isFavorite;
		isLoadNear = isNear;
		for (int i = 0 ; i < size ; i++)
		{
			String type = data.getString("p"+i+"type");
			Log.d("Type", type);
			String name = data.getString("p"+i+"name");
			double lat = data.getDouble("p"+i+"lat");
			double lng = data.getDouble("p"+i+"lng");
			GeoPoint point = staticClass.getPoint(lat, lng);
			PlaceInfo info = new PlaceInfo(name, type, 
					point.getLatitudeE6(), point.getLongitudeE6());
			PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(type);
			if (overlay != null)
			{
				overlay.addItems(point, name);
			} else {
				//Drawable draw = staticClass.getDrawable(type,this);
				Drawable draw = staticClass.getDrawable(type, KesuMap.this);
				draw.setBounds(-draw.getIntrinsicWidth()/2, -draw.getIntrinsicHeight()/2
						, draw.getIntrinsicWidth()/2, draw.getIntrinsicHeight()/2);
				Log.d("info", name+"-"+type+"-"+lat+"-"+lng);
				overlay = new PlaceOverlay(draw, type);
				overlay.addItems(point, name);
				mapPlaceOverlays.put(type, overlay);
				listPlaceOverlays.add(overlay);
			}
			placesInfo.put(info.getLatE6()+""+info.getLngE6(), info);
			if (!type.equals("Personal"))
			{
				if (isNear && isFavorite){
					int load = data.getInt("p"+i+"load");
					Log.d("load", load+","+info.getName()+","+info.getLatE6()+","+info.getLngE6());
					if (load == 1) 
						nearPlaces.put(info.getLatE6()+""+info.getLngE6(), info);
					else if (load == 2)
						favoritePlaces.put(info.getLatE6()+""+info.getLngE6(), info);
					else {
						nearPlaces.put(info.getLatE6()+""+info.getLngE6(), info);
						favoritePlaces.put(info.getLatE6()+""+info.getLngE6(), info);
					}
					load = 0;
				}else if (isNear) nearPlaces.put(info.getLatE6()+""+info.getLngE6(), info);
				else if (isFavorite) favoritePlaces.put(info.getLatE6()+""+info.getLngE6(), info);
			} else personalPlaces.put(info.getLatE6()+""+info.getLngE6(), info);
		}
		for (PlaceOverlay tmp:listPlaceOverlays)
		{
			try {
				if (tmp.size()>0)
					map.getOverlays().add(tmp);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
	}

	private void initPersonLocation(Bundle extras) {
		// TODO Auto-generated method stub
		double longitude =  extras.getDouble("longitude");
		double latitude = extras.getDouble("latitude");
		myLocation = new Location("reverseGeocoded");
		myLocation.setLatitude(latitude);
		myLocation.setLongitude(longitude);
		fListInfo = new LinkedList<FriendShortInfo>();
		int size = extras.getInt("size");
		Log.d("debug size",size+"");
		for (int i = 0 ; i < size ; i++)
		{
			FriendShortInfo fr = (FriendShortInfo) extras.getSerializable("friend"+i);
			if (fr!=null) fListInfo.add(fr);
		}
		
		myPoint = staticClass.getPoint(latitude, longitude);
		boolean focus = extras.getBoolean("focus");
		if (!focus) 
		{
			GeoPoint fPoint = staticClass.getPoint(extras.getDouble("flatitude")
					, extras.getDouble("flongitude"));
			map.getController().setCenter(fPoint);
			Log.d("focus", "false");
		}else map.getController().setCenter(myPoint);
		List<Overlay> ls = map.getOverlays();
		Drawable myDrawable = getResources().getDrawable(R.drawable.me);
		myDrawable.setBounds(-marker.getIntrinsicWidth()/2, 
					-marker.getIntrinsicHeight()/2, 
					marker.getIntrinsicWidth()/2, 
					marker.getIntrinsicHeight()/2);
		PersonOverlay myOverlay = new PersonOverlay(myDrawable,this);
		myOverlay.addItems(myPoint, getString(R.string.map_me));
		
		PersonOverlay fOverlay = null;
		Log.d("flist size", fListInfo.size()+"");
		if (fListInfo.size() > 0)
		{
			fOverlay = new PersonOverlay(staticClass.getDrawable("friend", this),this);
			for (FriendShortInfo fInfo : fListInfo)
	        {
				fOverlay.addItems(staticClass.getPoint(fInfo.getLatitude(), fInfo.getLongitude()), fInfo.getId());
	        }
		}
		
		Drawable point = getResources().getDrawable(R.drawable.flag);
		point.setBounds(-point.getIntrinsicWidth()/2, 
				-point.getIntrinsicHeight()/2, 
				point.getIntrinsicWidth()/2, 
				point.getIntrinsicHeight()/2);
		pointOverlay = new PointOverlay(point);
		pointOverlay.addItems(myPoint, "");
		map.getOverlays().add(pointOverlay);
		me=new MyLocationOverlay(this, map);
		map.getOverlays().add(me);
		map.getOverlays().add(myOverlay);
		if (fOverlay != null) 
		{
			map.getOverlays().add(fOverlay);
		}
		myLat = latitude;
		myLng = longitude;
	}

	private void initManageLocation(Bundle extras) {
		// TODO Auto-generated method stub
		String data = extras.getString("data");
		try {
			JSONArray listLocation = new JSONArray(data);
			listUserLocation = new LinkedList<LocationUserInfo>();
			for (int i = 0 ; i < listLocation.length() ; i++)
			{
				JSONObject object = listLocation.getJSONObject(i);
				LocationUserInfo info = new LocationUserInfo(
						object.getString("long"), object.getString("lat"), object.getString("time"));
				listUserLocation.add(info);
			}
			ManageOverlay manage = new ManageOverlay(listUserLocation);
			map.getOverlays().add(manage);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

	public void addNewPlace(String type, String name, String description,
			String address, GeoPoint point) {
		// TODO Auto-generated method stub
		PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(type);
		if (overlay != null)
		{
			overlay.addItems(point, name);
		} else {
			overlay = new PlaceOverlay(staticClass.getDrawable(type,this), type);
			overlay.addItems(point, name);
			mapPlaceOverlays.put(type, overlay);
			listPlaceOverlays.add(overlay);
			map.getOverlays().add(overlay);
		}
		List<CmtLocation> listCmt = new ArrayList<CmtLocation>();
		PlaceInfo pInfo = new PlaceInfo(listCmt, description, staticClass.user, name, type,address
				,point.getLatitudeE6(),point.getLongitudeE6(),false,true);
		placesInfo.put(point.getLatitudeE6()+""+point.getLongitudeE6(), pInfo);
		if (!pInfo.equals("Personal")) nearPlaces.put(point.getLatitudeE6()+""+point.getLongitudeE6(), pInfo);
		else personalPlaces.put(point.getLatitudeE6()+""+point.getLongitudeE6(), pInfo);
		map.postInvalidate();
		map.invalidate();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		new MenuInflater(getApplication()).inflate(R.menu.map_menu, menu);
		boolean result = super.onCreateOptionsMenu(menu);
		
		return (result);
	}
	private void filterFavorite()
	{
		isFavorite = true;
		if (!isLoadFav){
			isLoadFav = true;
			loadInfo.load("favorite");
		} else {
			enableFavorite();
		}
	}
	private void filterNear()
	{
			isNear = true;
			if (!isLoadNear)
			{
				isLoadNear = true;
				loadInfo.load("near");
			} else {
				enableNear();
			}
	}
	private void removeFavorite()
	{
		isFavorite = false;
		Iterator<Entry<String, PlaceInfo>> iter = favoritePlaces.entrySet().iterator();
		while (iter.hasNext()) {
			HashMap.Entry<String, PlaceInfo> entry = (HashMap.Entry) iter.next();
			PlaceInfo tmp = entry.getValue();
			removeItem(tmp);
		}
	}
	private void removeNear()
	{
		isNear = false;
		Iterator<Entry<String, PlaceInfo>> iter = nearPlaces.entrySet().iterator();
		while (iter.hasNext()) {
			HashMap.Entry<String, PlaceInfo> entry = (HashMap.Entry) iter.next();
			PlaceInfo tmp = entry.getValue();
			removeItem(tmp);
		}
	}
	private void removeItem(String type,String name,GeoPoint point)
	{
		PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(type);
		if (overlay != null) 
		{
				overlay.removeItems(point);
				Log.d("remove", type+":"+name);
		}
	}
	private void removeItem(String type,String name,int lat, int lng)
	{
		GeoPoint point = new GeoPoint(lat, lng);
		removeItem(type, name, point);
	}
	private void removeItem(PlaceInfo pi) {
		removeItem(pi.getType(), pi.getName(), pi.getLatE6(), pi.getLngE6());
	}
	
	private void enableFavorite()
	{
		Iterator<Entry<String, PlaceInfo>> iter = favoritePlaces.entrySet().iterator();
		while (iter.hasNext()) {
			HashMap.Entry<String, PlaceInfo> entry = (HashMap.Entry) iter.next();
			PlaceInfo tmp = entry.getValue();
			PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(tmp.getType());
			overlay.addItems(new GeoPoint(tmp.getLatE6(), tmp.getLngE6())
										, tmp.getName());
		}
	}
	private void enableNear()
	{
		Iterator<Entry<String, PlaceInfo>> iter = nearPlaces.entrySet().iterator();
		while (iter.hasNext()) {
			HashMap.Entry<String, PlaceInfo> entry = (HashMap.Entry) iter.next();
			PlaceInfo tmp = entry.getValue();
			PlaceOverlay overlay = (PlaceOverlay) mapPlaceOverlays.get(tmp.getType());
			overlay.addItems(new GeoPoint(tmp.getLatE6(), tmp.getLngE6())
										, tmp.getName());
		}
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		//System.out.println(item.);
		 
		switch(item.getItemId()){
			//--------------basic
			case R.id.map_menu_AddPlace:
				isAddingNewPlace = true;
				break;
			case R.id.map_menu_favoritePlace:
				
				removeNear();
				filterFavorite();
				map.postInvalidate();
				
				break;
			case R.id.map_menu_nearPlace:
				
				removeFavorite();
				filterNear();
				map.postInvalidate();
				
				break;
			case R.id.map_menu_all_place:
				if (!isNear)
				{
					filterNear();
				} else if (!isFavorite) 
				{
					filterFavorite();
				}
				map.postInvalidate();
				//TODO: save places, enable all
				break;
		}
		return(super.onOptionsItemSelected(item));
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			if(containerInfo.isShown())
			{
				containerInfo.setVisibility(View.INVISIBLE);
				return true;
			}
			else
				finish();
		}
		return(super.onKeyDown(keyCode, event));
	}
	private boolean isPublicPlace(String type){
		String []types = getResources().getStringArray(R.array.map_items_public);
		for(int i = 0; i < types.length; i++)
			if(type.equals(types[i]))
				return true;
		
		return false;
	}
	private void viewComment() {
		if(dlgCmt == null){
			dlgCmt = new MapCommentsView(this);
		}
		containerInfo.setVisibility(View.INVISIBLE);
		((MapCommentsView)dlgCmt).show(pInfo);
	}


	private void likePlace() {
		if (!pInfo.isLike())
		{
			staticClass.socket.println("<like><lat>"+pInfo.getLatE6()+"<lng>"+pInfo.getLngE6());
			pInfo.setLike(true);
			favoritePlaces.put(pInfo.getLatE6()+""+pInfo.getLngE6(), pInfo);
			btnLike.setText("Dislike");
		} else {
			staticClass.socket.println("<dislike><lat>"+pInfo.getLatE6()+"<lng>"+pInfo.getLngE6());
			pInfo.setLike(false);
			favoritePlaces.remove(pInfo.getLatE6()+""+pInfo.getLngE6());
			btnLike.setText("Like");
		}
	}
	private void direction(double latS,double lngS,double latD,double lngD){
		Intent intent = new Intent(android.content.Intent.ACTION_VIEW, 
		Uri.parse("http://maps.google.com/maps?saddr="+latS+","+lngS+"&daddr="+latD+","+lngD));
		startActivity(intent);
	}
	@Override
	public void onClick(View v) {
		pointOverlay.removeItem();
		if(v == btnAdd){
			containerConfirmAdd.setVisibility(View.INVISIBLE);
			isAddingNewPlace = false;
			if(dlgAddPlace == null)
				dlgAddPlace = new MapAddLocation(this);
			((MapAddLocation)dlgAddPlace).show(tapPoint,this);
			
		}
		else if(v == btnCancel){
			pointOverlay.removeItem();
			containerConfirmAdd.setVisibility(View.INVISIBLE);
			isAddingNewPlace = false;
			map.postInvalidate();
		}
		else if(v == btnViewCmt){
			viewComment();
		}
		else if(v == btnLike){
			likePlace();
		}
		else if(v == btnEdit){
			Log.d("Edit", "here");
			containerInfo.setVisibility(View.INVISIBLE);
			if(dlgAddPlace == null)
				dlgAddPlace = new MapAddLocation(this);
			((MapAddLocation)dlgAddPlace).show(pInfo,this);
		}
		else if(v == btnDirect){
			Log.d("Debuging", pInfo.getLat()+","+pInfo.getLng());
			direction(myLat, myLng, pInfo.getLat(), pInfo.getLng());
		}
	}
	public void setPlaceInfo(String name, String type, String address, String description) {
		String content = formatString(getString(R.string.map_info_name), name)
					   + formatString(getString(R.string.map_info_type), type)
					   + formatString(getString(R.string.map_info_address), address)
					   + formatString(getString(R.string.map_info_describe), "")
					   + description.replaceAll("\n", "<br/>");
						;
		txtPlaceInfo.setText(Html.fromHtml(content));
	}
	private String formatString(String atribute, String content){
		return "<b>" + atribute + ": </b>" + content.replaceAll("\n", "<br/>") + "<br/>";
	}
	@Override
	public void onResume() {
		super.onResume();
		
		//me.enableCompass();
	}		
	@Override
	public void onPause() {
		super.onPause();
		//me.disableCompass();
	}	
	public void cancel()
	{
		containerInfo.setVisibility(View.INVISIBLE);
		map.postInvalidate();
	}
}

